package kr.pe.asuraho;

import static kr.pe.asuraho.StaticMethods.crontabCode;
import static kr.pe.asuraho.StaticMethods.nvl;

import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class SchedulerListener implements ServletContextListener {
	
//	@Override
	public void contextDestroyed(ServletContextEvent context) {
		try {
			Scheduler sd = StdSchedulerFactory.getDefaultScheduler();
			sd.deleteJob(new JobKey("HibogoJob"));
			sd.shutdown();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		
		DBConn.close();
	}

//	@Override
	public void contextInitialized(ServletContextEvent context) {
		Map<String, Object> settingInfo = DBConn.getSqlSession().selectOne("kr.pe.asuraho.selectTorSetting");
		String job_interval_code = nvl(settingInfo.get("job_interval"));
		String interval = crontabCode(job_interval_code);
		
		JobDetail job = JobBuilder.newJob(SchedulerJob.class).withIdentity("HibogoJob").withDescription("스따또~").build();
		
		Trigger trigger = TriggerBuilder.
							newTrigger().
							withIdentity("HibogoTrigger").
							withSchedule(CronScheduleBuilder.cronSchedule(interval)).
							build();
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.scheduleJob(job, trigger);
			scheduler.start();
		} catch (SchedulerException e) {
		}
	}
}